package cn.jljiayu.business.sys.oauth.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 登录url
 * 2022/5/21 8:47 下午
 *
 * @author zhangby
 **/
@Controller
public class SsoLoginController {

    @GetMapping(value = {"login"})
    public String login() {
        return "login";
    }

    /**
     * 统一登录
     *
     * @param redirectUrl
     * @return
     */
    @GetMapping("/ssoLogin")
    private String ssoLogin(String redirectUrl,
                            @RequestParam(defaultValue = "hash") String redirectType,
                            String redirectHash) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof OAuth2AuthenticationToken) {
            OAuth2AuthenticationToken auth2AuthenticationToken = (OAuth2AuthenticationToken) authentication;
            DefaultOidcUser defaultOidcUser = (DefaultOidcUser) auth2AuthenticationToken.getPrincipal();
            String accessToken = defaultOidcUser.getIdToken().getTokenValue();
            if ("hash".equals(redirectType)) {
                return "redirect:" + redirectUrl + "/#/" + redirectHash + "?respCode=0000&accessToken=" + accessToken;
            } else {
                return "redirect:" + redirectUrl + "?respCode=0000&accessToken=" + accessToken;
            }
        } else {
            return "ssoLoginResult";
        }
    }
}